// pages/worker/payNow/payNow.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 时间日期选择器
    columns: {},
    showPop: false, //展示弹出层
    showBot: true, //展示底部操作
    sysTypeDetail: null, //支付单价 单位等信息
    address: null, // 默认地址json     addressId
    time: null, //上门时间
    sysSku: null, //服务类型列表
    activeIndex: null,
    stepper: '1', //选择服务时长    //如果支付不是按照时常 支付时候不要传
    totalMoney: 0, //订单总金额  直接点击服务
    totalTimeMoney: 0, //按次金额
    deposit: null, //定金
    typeDetailId: null,
    getDetailByTypeId: null, //通过服务分类id获取服务详情
    quan: null, //优惠券信息
    use: false, //是否使用优惠券
    isgetLocalQuan: false,
  },
  // 点击跳转到地址列表
  toAddress() {
    wx.navigateTo({
      url: '/pages/mine/address/address',
    })
  },
  //获取地址
  getAddress() {
    var postObj = {
      url: '/mobileUser/address/list',
      method: 'get'
    }
    app.request.wxRequest(postObj).then(res => {
      if (res.data.code === 200) {
        let data = res.data.rows

        if (data.length == 0) {
          this.setData({
            address: null
          })
        } else if (data.length == 1) {
          this.setData({
            address: data[0]
          })
          // console.log(data, this.data.address);
        } else {
          data.forEach((items, i) => {
            if (items.defalut == "1") {
              this.setData({
                address: items
              })
            }
          })
        }




      }
    })
  },
  //点击跳转到优惠券  需要判断账户有没有优惠券
  toQuan() {

    var postObj = {
      url: '/mobileUser/receive/getNotCoupon?pageNum=1' + '&pageSize=6' + '&num=0',
      method: 'get'
    }
    app.request.wxRequest(postObj).then(res => {
      if (res.data.code === 200) {
        console.log('优惠券', res)

        var rows = res.data.rows
        if (rows.length == 0) {
          wx.showToast({
            title: '暂无优惠券',
            image: '../../../assets/error.png',
            duration: 500,
            mask: true
          })
        } else {
          wx.navigateTo({
            url: '/pages/mine/quan/quan',
          })
        }
      }
    })


  },
  // 点击类型
  clickType(e) {

    var index = Number(e.currentTarget.dataset.index) //服务类型的下标
    var totalMoney = this.data.sysSku[index].money //本条服务类型的金额
    this.setData({
      activeIndex: index,
      // totalMoney: totalMoney
    })
    // console.log(index);

    this.getTotal()
  },
  // 时间日期选择器
  setColumns() {
    // columns 

    var day = {
      'day': app.util.getDay30After(),
      'hour': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', ],
      'minute': ['00', '30']
    }
    var columns = [{
        values: day['day'],
        key: 'day',
        defaultIndex: 0
      },
      {
        values: day['hour'],
        key: 'hour',
        defaultIndex: 8
      },
      {
        values: day['minute'],
        key: 'minute',
        defaultIndex: 0
      },
    ]
    this.setData({
      columns: columns
    })
  },
  showPopup() {
    this.setData({
      showPop: true,
      showBot: false
    });
  },
  onClose() {
    this.setData({
      showPop: false,
      showBot: true
    });
  },
  onConfirm(event) {
    // const {
    //   picker,
    //   value,
    //   index
    // } = event.detail;
    // console.log(`当前值：${value}, 当前索引：${index}`);
    console.log(event);
    var time = event.detail.value[0] + ' ' + event.detail.value[1] + ':' + event.detail.value[2]
    this.setData({
      time: time
    })
    this.onClose()
  },
  // 获取服务详情  /mobileUser/type/getDetail/{typeId}
  queryParentList(typeId) {
    var postObj = {
      url: `/mobileUser/type/getDetail/${typeId}`,
      method: 'get'
    }
    app.request.loginRequest(postObj).then(res => {
      if (res.data.code === 200) {
        var data = res.data.data
        var sysSku = data.sysSkuSku.sysSku
        sysSku.forEach((item, i) => {
          console.log(item);

          item.data = JSON.parse(item.data)
          var arr = []
          var string = ''
          for (const key in item.data) {
            if (item.data.hasOwnProperty(key)) {
              const element = item.data[key];
              var str = key + "：" + element
              arr.push(str)

              string = string.concat(str).concat(' ')
            }
          }
          string = string.concat(" /￥" + item.money)
          item.arr = arr
          item.string = string
        })
        this.setData({
          sysSku: sysSku,
          deposit: data.sysSkuSku.sysTypeDetail.deposit,
          typeDetailId: data.typeDetailId,
          sysTypeDetail: data.sysSkuSku.sysTypeDetail
        })
        //加入有定金就支付定金  所有订单总金额就是定金

        this.getDetailByTypeId(data.typeDetailId)
        console.log(data);

      }
    })
  },
  // 通过服务分类id获取服务详情 manage/mobileUser/getDetailByTypeId
  getDetailByTypeId(typeDetailId) {
    var postObj = {
      url: `/mobileUser/getDetailByTypeId`,
      method: 'post',
      data: {
        typeDetailId: typeDetailId
      }
    }
    app.request.loginRequest(postObj).then(res => {
      if (res.data.code === 200) {
        var data = res.data.data
        console.log('支付方式判断', data);
        // charge2计费方式 1-按时间 2-直接勾选
        // unit2费用单位 1-每平方米  2-每小时 3-每次(数据字典)
        var unit = data.unit
        var unitName = ''
        if (unit == '1') {
          unitName == '每平方米'
        } else if (unit == '2') {
          unitName == '每小时'
        } else if (unit == '3') {
          unitName == '每次'
        }

        this.setData({
          getDetailByTypeId: data
        })
      }
    })
  },
  //计算总金额 totalMoney  按服务类型
  getTotal() {
    var quan = this.data.quan
    var index = this.data.activeIndex

    if (!!quan) { //如果选择了券


      if (index != null && index != undefined) { //如果点击过服务

        if (this.data.sysSku[index].money >= this.data.quan.needMoney) { //达到满减
          var money = Number(this.data.sysSku[index].money - this.data.quan.money)
          console.log('服务金额', this.data.sysSku[index].money);
          console.log('券金额', this.data.quan.money);
          console.log('达到满减', this.data.quan.needMoney);
          console.log('支付金额', money);


          this.setData({
            totalMoney: (money > 0) ? money : 0,
            use: true,
          })
        } else { //未达到满减
          var money = this.data.sysSku[index].money
          wx.showToast({
            title: '优惠券不可用哦！',
            image: '../../../assets/error.png',
            duration: 500,
            mask: true
          })
          this.setData({
            totalMoney: money,
            use: false,
          })
        }


      } else { //没有点击过服务
        this.setData({
          totalMoney: 0
        })
      }



    } else { //如果没有选择券

      if (index != null && index != undefined) { //如果点击过服务
        var money = this.data.sysSku[index].money

        this.setData({
          totalMoney: money
        })
      } else { //没有点击过服务
        this.setData({
          totalMoney: 0
        })
      }




    }
  },
  // 选择服务时长
  onChangestepper(event) {
    console.log('次数', event.detail);

    this.setData({
      stepper: event.detail
    })
    this.getTimeTotal()
  },
  // 选择服务时长  计算金额
  getTimeTotal() {
    console.log("次数信息", this.data.sysTypeDetail);

    var oneTime = +this.data.getDetailByTypeId.money
    var times = +this.data.stepper
    var quan = this.data.quan

    if (!!quan) { //如果选择了券


      if (times * oneTime >= this.data.quan.needMoney) { //达到满减
        var money = Number(times * oneTime - this.data.quan.money)
        // console.log('服务金额', this.data.sysSku[index].money);
        // console.log('券金额', this.data.quan.money);
        // console.log('达到满减', this.data.quan.needMoney);
        // console.log('支付金额', money);
        this.setData({
          totalTimeMoney: (money > 0) ? money : 0,
          use: true,
        })
      } else { //未达到满减
        var money = times * oneTime
        // wx.showToast({
        //   title: '优惠券不可用哦！',
        //   image: '../../../assets/error.png',
        //   duration: 500,
        //   mask: true
        // })
        this.setData({
          totalTimeMoney: money,
          use: false,
        })
      }

    } else { //如果没有选择券
      this.setData({
        totalTimeMoney: times * oneTime
      })
    }
  },
  // 立即预约  http://192.168.0.113:8082/manage/mobileUser/createOrderService
  yuyueNow() {

    if (!!!this.data.address) {
      wx.showToast({
        title: '添加地址!',
        image: '../../../assets/error.png',
        duration: 500,
      })
    } else if (!!!this.data.time) {
      wx.showToast({
        title: '上门时间!',
        image: '../../../assets/error.png',
        duration: 500,
      })
    } else if (this.data.sysSku.length > 0 && (this.data.activeIndex == null || this.data.activeIndex == undefined)) {
      wx.showToast({
        title: '服务类型!',
        image: '../../../assets/error.png',
        duration: 500,
      })
    } else {
      var data = null
      if (this.data.getDetailByTypeId.charge == '2') {
        // 选择服务
        data = {
          addressId: this.data.address.addressId,
          typeDetailId: this.data.typeDetailId,
          money: this.data.totalMoney,
          totalMoney: this.data.sysSku[this.data.activeIndex].money,
          serviceTime: this.data.time,
          total: this.data.getDetailByTypeId.charge == "2" ? "1" : this.data.stepper,
          couponId: this.data.use == true ? this.data.quan.couponId : '',
          skuId: this.data.sysSku[this.data.activeIndex].skuId,
        }
      } else if (this.data.getDetailByTypeId.charge == '1') {
        // 次 //按次服务
        var oneTime = +this.data.getDetailByTypeId.money
        var times = +this.data.stepper
        data = {
          addressId: this.data.address.addressId,
          typeDetailId: this.data.typeDetailId,
          money: this.data.totalTimeMoney,
          totalMoney: oneTime * times,
          serviceTime: this.data.time,
          total: this.data.getDetailByTypeId.charge == "2" ? "1" : this.data.stepper,
          couponId: this.data.use == true ? this.data.quan.couponId : '',

        }
      }




      var postObj = {
        url: `/mobileUser/createOrderService`,
        method: 'post',
        data: data
      }
      app.request.wxRequest(postObj).then(res => {
        if (res.data.code === 200) {
          console.log('下单', res);
          this.wechatPay(res.data.data)
        }
      })
    }


  },

  // wechatPay  微信小程序 支付
  wechatPay(orderId) {
    var postObj = {
      url: `/mobileUser/payOrderService`,
      method: 'post',
      data: {
        orderId: orderId,
        payType: 2
      }
    }
    app.request.wxRequest(postObj).then(res => {
      if (res.data.code === 200) {
        console.log('支付返回值', res);
        // wx.showToast({
        //   title: '下单成功',
        //   image: '../../../assets/success.png',
        //   duration: 500,
        //   mask: true,
        //   success: () => {
        //     wx.reLaunch({
        //       url: '/pages/mine/order/order',
        //     })
        //   }
        // })
        let prepay = res.data.data
        return new Promise((resolve, reject) => {
            wx.requestPayment({
              "timeStamp": prepay.timeStamp,
              "nonceStr": prepay.nonceStr,
              "package": `prepay_id=${prepay.prepayId}`,
              "signType": 'MD5',
              "paySign": prepay.sign,
              "success": res => {
                wx.reLaunch({
                  url: '/pages/mine/order/order',
                }) //我的订单
                console.log("订单确定", res);
                resolve(res);
              },
              "fail": res => {
                wx.reLaunch({
                  url: '/pages/mine/order/order',
                }) //我的订单
                console.log("订单取消", res);
                reject(res);
              }
            });
          })
          .then(res => {
            const data = res.data;
            console.log("payOrder返回值", data);
          });
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    var typeId = options.typeId

    //获取服务详情
    that.queryParentList(typeId)
    // console.log(that.data.typeDetailId);

    // 清除本地保存的券
    wx.removeStorageSync('quan')
    // 清除后从本地拿
    that.setData({
      isgetLocalQuan: true
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    that.setColumns()

    that.getAddress() //默认地址

    //本地拿优惠券
    if (that.data.isgetLocalQuan == false) {
      wx.removeStorageSync('quan')
    } else if (that.data.isgetLocalQuan == true) {
      var local = wx.getStorageSync('quan')
      if (!!local) {
        var quan = JSON.parse(local)
        that.setData({
          quan: quan
        })
      } else {
        that.setData({
          quan: quan
        })
      }
    }
    //一进去页面展示支付金额
    // activeIndex

    this.getTotal()


    setTimeout(function () {
      console.log(222);
      if (that.data.getDetailByTypeId.charge == '1') {
        console.log(11111);

        that.getTimeTotal()
      }
    }, 500)


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})